package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.reposity.BankTypeRepository;
import com.xinhe.web.reposity.MemberRepository;
import com.xinhe.web.response.MemberView;
import com.xinhe.web.util.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.util.Date;
import java.util.Objects;

@Service

public class BankTypeService {
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }
    @Autowired
    BankTypeRepository bankTypeRepository;

    public QueryResults<BankType> pageBankType(String name, String value, String remark, int pageNum, int pageSize) {
        QBankType qBankType = QBankType.bankType;
        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qBankType.name.eq(name));
        }
        if (!Objects.isNull(value)) {
            builder.and(qBankType.value.eq(value));
        }
        return queryFactory.select(
                        Projections.bean(
                                BankType.class,
                                qBankType.name,
                                qBankType.value,
                                qBankType.id
                        )
                ).from(qBankType)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }


    public void saveModel(String name, String value, String remark) {
        BankType bankType = new BankType();
        bankType.setId(Snowflake.generateId());
        bankType.setName(name);
        bankType.setValue(value);
        bankTypeRepository.save(bankType);
    }

    public void delete(Long bankTypeId) {
        bankTypeRepository.deleteById(bankTypeId);
    }

    public Result<BankType> findById(Long bankTypeId) {
        return Result.ok(bankTypeRepository.findById(bankTypeId).get());
    }
}
